<template>
  <div class="container">
    <el-upload
      ref="upload"
      action=""
      :auto-upload="false"
      :http-request="serverUpload"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
    </el-upload>
  </div>
</template>

<script>

import {getFileOssConfig, uploadFile} from "../../api";
import axios from 'axios'

export default {
  name: "upload",
  data() {
    return {
      name: 'upload',
      ossConfig: {}
    }
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit();
    },
    serverUpload({file}) {
      const formData = new FormData();
      //参数顺序有关 file必须放在最后
      formData.append("key", this.ossConfig.dir + file.name)
      for(let key in this.ossConfig) {
        formData.append(key, this.ossConfig[key])
      }
      formData.append("file", file);

      axios.post(this.ossConfig.host, formData).then(res => {
        console.log("success");
        this.$refs.upload.clearFiles()
      })
    }
  },
  mounted() {
    getFileOssConfig().then(res => {
      this.ossConfig = res.data;
    })
  }
}
</script>

<style scoped>
.container {
  margin: 30px;
}
</style>
